import {
  Table,
  Tag,
  Space,
  Modal,
  Button,
  Checkbox,
  Row,
  Col,
  Input,
  message,
  Popconfirm,
  Typography,
} from 'antd';
import { RolePermission } from '../../utils/hooks';
import Config, { RouterMaper, ApiMaper } from '../../Config';
import { useState, useRef, useReducer } from 'react';
import axios from 'axios';
import { selectApi_permission } from '../../redux/Slice/userSlice';
import api from '../../utils/api';
import { useSelector } from 'react-redux';
const checkRoute = (enSetClicked, AllList) => {
  if (enSetClicked == undefined) return [];
  let routeList = [];
  let res = [];
  for (let i = 0; i < AllList.length; i++) {
    routeList.push(AllList[i].routeName);
  }
  for (let i = 0; i < enSetClicked.length; i++) {
    let index = routeList.indexOf(enSetClicked[i]);
    if (index > -1) res.push(AllList[index].routeId);
  }
  return res;
};

const checkApi = (enSetClicked, AllList) => {
  if (enSetClicked == undefined) return [];
  let ApiList = [];
  let res = [];
  for (let i = 0; i < AllList.length; i++) {
    ApiList.push(AllList[i].apiName);
  }
  for (let i = 0; i < enSetClicked.length; i++) {
    let index = ApiList.indexOf(enSetClicked[i]);
    if (index > -1) res.push(AllList[index].apiId);
  }
  return res;
};
function clickReducer(state, action) {
  switch (action.type) {
    case 'initial':
      return { ...state, isModalVisible: action.payload.isModalVisible };
    case 'show':
      return {
        isModalVisible: true,
        RoleName: action.payload.RoleName,
        InitRoute: checkRoute(action.payload.ClickedRoute, action.payload.routeList),
        InitApi: checkApi(action.payload.ClickApi, action.payload.apiList),
        roleId: action.payload.roleId,
      };
    case 'hidden':
      return {
        ...state,
        isModalVisible: false,
      };
  }
  return state;
}
export default () => {
  const [state, dispatch] = useReducer(clickReducer, {
    isModalVisible: false,
    RoleName: '',
    InitApi: [],
    InitRoute: [],
    roleId: null,
  });
  const [refresh, Setrefresh] = useState(false);
  const { isLoading, data, apiList, routeList, SetData } = RolePermission(refresh);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const [addRoleModel, setaddRoleModel] = useState(false);
  const inputVal = useRef(null);
  const apiPermission = useSelector(selectApi_permission);
  let checkedRoute = null,
    checkedApi = null,
    checkedId;
  const showModal = record => {
    return () => {
      dispatch({
        type: 'show',
        payload: {
          roleId: record.roleId,
          RoleName: record.roleName,
          ClickedRoute: record.route,
          ClickApi: record.api,
          routeList: routeList,
          apiList: apiList,
        },
      });
    };
  };
  const handleOk = () => {
    setConfirmLoading(true);
    if (checkedRoute == null) checkedRoute = state.InitRoute;
    if (checkedApi == null) checkedApi = state.InitApi;
    let routeInsert = [],
      routeDelete = [];

    let apiInsert = [],
      apiDelete = [];

    for (let i = 0; i < routeList.length; i++) {
      if (
        checkedRoute.indexOf(routeList[i].routeId) > -1 &&
        state.InitRoute.indexOf(routeList[i].routeId) == -1
      ) {
        routeInsert.push(routeList[i].routeId);
      } else if (
        checkedRoute.indexOf(routeList[i].routeId) == -1 &&
        state.InitRoute.indexOf(routeList[i].routeId) > -1
      ) {
        routeDelete.push(routeList[i].routeId);
      }
    }
    for (let i = 0; i < apiList.length; i++) {
      if (
        checkedApi.indexOf(apiList[i].apiId) > -1 &&
        state.InitApi.indexOf(apiList[i].apiId) == -1
      ) {
        apiInsert.push(apiList[i].apiId);
      } else if (
        checkedApi.indexOf(apiList[i].apiId) == -1 &&
        state.InitApi.indexOf(apiList[i].apiId) > -1
      ) {
        apiDelete.push(apiList[i].apiId);
      }
    }

    axios
      .post(Config.baseURL + '/role/changePermission', {
        roleId: state.roleId,
        routeInsert: routeInsert,
        routeDelete: routeDelete,
        apiInsert: apiInsert,
        apiDelete: apiDelete,
      })
      .then(response => {
        if (response.data.code === 1) {
          message.success('修改成功', 1);
          setTimeout(() => {
            Setrefresh(!refresh);
            dispatch({ type: 'hidden' });
            setConfirmLoading(false);
          }, 2);
        } else {
          message.error('修改失败 ' + response.data.message, 2);
          setConfirmLoading(false);
        }
      })
      .catch(error => {
        message.error('修改失败,服务器错误', 1);
        setConfirmLoading(false);
      });
  };

  const handleCancel = () => {
    dispatch({ type: 'hidden' });
  };

  const deleteRole = record => {
    return () => {
      axios
        .post(Config.baseURL + '/role/deleteRole', {
          roleId: record.roleId,
        })
        .then(res => {
          console.log(res);
          if (res.data.code == 1) {
            message.success('修改成功', 1);
            setTimeout(() => {
              Setrefresh(!refresh);
            }, 2);
          } else if (res.data.code >= 10000) message.error(res.data.message, 1);
          else {
            message.error('修改失败', 1);
          }
        })
        .catch(err => {
          console.log(err);
          message.error('出错', 1);
        });
    };
  };

  const tagColor = [
    'magenta',
    'red',
    'volcano',
    'orange',
    'gold',
    'lime',
    'green',
    'cyan',
    'blue',
    'geekblue',
  ];
  const columns = [
    {
      title: '序号',
      dataIndex: 'roleId',
      key: 'roleId',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      render: text => <a>{text}</a>,
    },
    {
      title: '路由权限',
      dataIndex: 'route',
      key: 'route',
      render: tags => (
        <>
          {tags.map((tag, index) => {
            let color = tagColor[index % 10];
            return (
              <Tag color={color} key={tag}>
                {RouterMaper.get(tag)}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作权限',
      key: 'api',
      dataIndex: 'api',
      render: tags => (
        <>
          {tags.map((tag, index) => {
            let color = tagColor[index % 10];
            return (
              <Tag color={color} key={tag}>
                {ApiMaper.get(tag)}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record, index) => (
        <Space size="middle">
          <Button
            type="primary"
            disabled={api('role:edit', apiPermission)}
            onClick={showModal(record)}
          >
            修改
          </Button>
          <Popconfirm
            title="你确定要删除吗?"
            onConfirm={deleteRole(record)}
            okText="是"
            cancelText="否"
            disabled={api('role:delete', apiPermission)}
          >
            <Typography.Link>删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const addRole = () => {
    setaddRoleModel(true);
  };

  const addRoleOk = () => {
    axios
      .post(Config.baseURL + '/role/addRole', { rolename: inputVal.current.state.value })
      .then(res => {
        console.log(res);
        if (res.data.code == 1) {
          setaddRoleModel(false);
          Setrefresh(!refresh);
          message.success('修改成功', 1);
        } else if (res.data.code >= 10000) message.error(res.data.message, 1);
        else {
          message.error('修改失败', 1);
        }
      })
      .catch(err => {
        message.error('出错', 1);
      });
  };

  const addRoleCancel = () => {
    setaddRoleModel(false);
  };

  return (
    <>
      <Button
        type="primary"
        style={{ float: 'left', margin: '15px' }}
        onClick={addRole}
        disabled={api('role:add', apiPermission)}
      >
        增加角色
      </Button>
      <Table
        loading={isLoading}
        columns={columns}
        dataSource={data}
        pagination={{ position: ['bottomCenter'] }}
      />
      <Modal
        confirmLoading={confirmLoading}
        destroyOnClose={true}
        title={state.RoleName}
        visible={state.isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        style={{ padding: '10px' }}
        okText="确认"
        cancelText="取消"
      >
        <Row>
          <Col span={5}>
            <Tag color="blue" style={{ fontSize: '15px' }}>
              路由权限:
            </Tag>
          </Col>
          <Col span={19}>
            <Checkbox.Group
              onChange={value => {
                checkedRoute = value;
              }}
              defaultValue={state.InitRoute}
              options={routeList.map(value => {
                return { value: value.routeId, label: RouterMaper.get(value.routeName) };
              })}
            />
          </Col>
        </Row>
        <Row style={{ marginTop: '20px' }}>
          <Col span={5}>
            <Tag color="blue" style={{ fontSize: '15px' }}>
              操作权限:
            </Tag>
          </Col>
          <Col span={19}>
            <Checkbox.Group
              onChange={value => {
                checkedApi = value;
              }}
              defaultValue={state.InitApi}
              options={apiList.map(value => {
                return { value: value.apiId, label: ApiMaper.get(value.apiName) };
              })}
            />
          </Col>
        </Row>
      </Modal>
      <Modal
        visible={addRoleModel}
        title="增加角色"
        okText="确认"
        cancelText="取消"
        style={{ padding: '10px' }}
        onOk={addRoleOk}
        onCancel={addRoleCancel}
      >
        <Input placeholder="2至6个中文字符" ref={inputVal} />
      </Modal>
    </>
  );
};
